package jee.boot.module.log.local;

import jee.boot.common.utils.JsonMapper;
import jee.boot.module.log.service.LogEntityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class LogThread extends Thread {

    public static LinkedBlockingQueue<InterceptorLogEntity> interceptorLogQueue = new LinkedBlockingQueue<>();
    private static Logger logger = LoggerFactory.getLogger(LogThread.class);
    @Autowired
    private LogEntityService logEntityService;

    @Override
    public void run() {
        logger.debug("start the InterceptorLog  thread");
        while (true) {
            try {
                InterceptorLogEntity entity = interceptorLogQueue.take();
                Map<String, Object> log = entity.getLog();
                logger.debug("insert local log: " + JsonMapper.toJsonString(log));
                logEntityService.insertLocalLog(log);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

}
